package com.czn.shoppingmall.controller.backend.seller;

import com.alibaba.fastjson.JSON;
import com.czn.shoppingmall.common.Const;
import com.czn.shoppingmall.common.ServerResponse;
import com.czn.shoppingmall.domain.User;
import com.czn.shoppingmall.service.IUserService;
import com.czn.shoppingmall.util.RequestUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.URLDecoder;

@RestController
@RequestMapping("/seller/")
public class SellerController {

    @Autowired
    private IUserService iUserService;


    /**
     * 商家用户登陆
     * @param
     * @param
     * @param session
     * @return
     */
    @RequestMapping(value = "login",method = RequestMethod.POST)
//    public ServerResponse login(@RequestParam String username, @RequestParam String password, HttpSession session){
    public ServerResponse login(HttpServletRequest request, HttpSession session){
        try {
            String contentType = request.getContentType();
            String username;
            String password;
            if (contentType!=null && !contentType.isEmpty() && contentType.equalsIgnoreCase("application/json; charset=utf-8")) {
                String inputStr = RequestUtil.getInputString(request);
                username = JSON.parseObject(inputStr).getString("username");
                password = JSON.parseObject(inputStr).getString("password");
            }else {
                username = URLDecoder.decode(request.getParameter("username"),"UTF-8");
                password = URLDecoder.decode(request.getParameter("password"),"UTF-8");
            }
            if (StringUtils.isBlank(username) || StringUtils.isBlank(password)){
                return ServerResponse.createByIllegalArgument();
            }
            ServerResponse response = iUserService.login(username, password);
            if (!response.isSuccess()) {
                return response;
            }
            User user = (User)response.getData();
            if (iUserService.checkRole(user.getRole(), Const.Role.ROLE_SELLER)) {
                // 用户登陆成功，将其信息放入session中
                session.setAttribute(Const.CURRENT_USER, user);
                return response;
            }
            return ServerResponse.createByErrorMessage("非商家用户");
        } catch (IOException e) {
            e.printStackTrace();
            return ServerResponse.createByIllegalArgument();
        }
    }

    /**
     * 注册商家用户
     * @param
     * @return
     */
    @RequestMapping(value = "register", method = RequestMethod.POST)
    public ServerResponse register(@RequestBody User user){
        if (null == user) {
            return ServerResponse.createByIllegalArgument();
        }
        user.setRole(Const.Role.ROLE_SELLER);
        return iUserService.register(user);
    }
/*    public ServerResponse register(HttpServletRequest request) throws IOException {
        String contentType = request.getContentType();
        User user = null;
        if (contentType!=null && !contentType.isEmpty() && contentType.equalsIgnoreCase("application/json; charset=utf-8")) {
            String inputStr = RequestUtil.getInputString(request);
            System.out.println(inputStr);
            user = JSON.parseObject(inputStr,User.class);
        }else {
            user = new User(URLDecoder.decode(request.getParameter("username"),"UTF-8"),
                    URLDecoder.decode(request.getParameter("password"),"UTF-8"),
                    URLDecoder.decode(request.getParameter("realname"),"UTF-8"),
                    URLDecoder.decode(request.getParameter("email"),"UTF-8"),
                    URLDecoder.decode(request.getParameter("phone"),"UTF-8"),
                    URLDecoder.decode(request.getParameter("question"),"UTF-8"),
                    URLDecoder.decode(request.getParameter("answer"),"UTF-8"),
                    Integer.valueOf(request.getParameter("role"))
                    );
        }
        if (null == user) {
            return ServerResponse.createByIllegalArgument();
        }
        user.setRole(Const.Role.ROLE_SELLER);
        return iUserService.register(user);
    }*/

    /**
     * 更新个人信息
     * @param user
     * @param session
     * @return
     */
    @RequestMapping(value = "update_information", method = RequestMethod.POST)
    public ServerResponse update(User user,HttpSession session){
        User currentUser = (User) session.getAttribute(Const.CURRENT_USER);
        if (null == currentUser) {
            return ServerResponse.createByNeedLogin("用户未登录,请先登陆");
        }
        if (!iUserService.checkRole(currentUser.getRole(),Const.Role.ROLE_SELLER)) {
            return ServerResponse.createByErrorMessage("不是商家，无法修改商家信息");
        }
        user.setId(currentUser.getId());
        user.setUsername(currentUser.getUsername());
        user.setRole(currentUser.getRole());
        ServerResponse response = iUserService.update(user);
        if (!response.isSuccess()) {
            return response;
        }
        // 更新session中存储的个人信息
        User updateUser = (User)response.getData();
        updateUser.setUsername(currentUser.getUsername());
        updateUser.setRole(currentUser.getRole());
        session.setAttribute(Const.CURRENT_USER, updateUser);
        return response;
    }

    /**
     * 获取商家个人信息
     * @param session
     * @return
     */
    @RequestMapping("get_information")
    public ServerResponse getUserInformation(HttpSession session) {
        User currentUser = (User) session.getAttribute(Const.CURRENT_USER);
        if (null == currentUser) {
            return ServerResponse.createByNeedLogin("用户未登录,请先登陆");
        }
        return iUserService.getUserInformation(currentUser.getId());
    }

}
